<template>
  <div>
    <z-form-template
        :def="control.def"
        @fire="control.onFire"
        @ready="control.onReady"
    >
      <template #after="scope">
        <div v-if="scope.curFormCtx">
          <el-button type="primary"
                     @click="handleFormSubmit(scope.curFormCtx.getCurForm())">提交</el-button>
          <el-button @click="saveLocalStorage">保存配置</el-button>
          <el-button @click="exportStorage">导出配置</el-button>
        </div>
      </template>
    </z-form-template>
  </div>
</template>

<script>
import {FormBase} from "@/zpkgs/hooks/form";

export default {
  name: "DemoFormControl",
  setup(props, ctx) {

    const DB_NAME = 'demo-form-control'
    let cached = {}

    let control =  {
      def: {
        properties: {
          url: {
            ...FormBase('异步生成表单API地址', {
              ui: {
                widget: 'CusInput',
                widgetConfig: {
                }
              }
            }),
            rules: [],
          },
          option: {
            type: 'object',
            properties: {
              url: {
                ...FormBase('表单提交地址', {
                  ui: {
                    widget: 'CusInput',
                    widgetConfig: {
                    }
                  }
                }),
                rules: [],
              },
              detailUrl: {
                ...FormBase('表单获取信息地址', {
                  ui: {
                    widget: 'CusInput',
                    widgetConfig: {
                    }
                  }
                }),
                rules: [],
              },
            }
          }
        }
      },
      onFire([type, args, ctx] = []) {
        // console.log(type, args, ctx)
        if (type === 'updateValue') {
          // let d = ctx.getDataSync()
          // console.log(d)

        }
      },
      async onReady(e) {
        cached = await ZY_EXT.store.getItem(DB_NAME);
        if (!cached) {
          cached = {
            url: 'http://192.168.1.67:7001/form2',
            option: {
              url: 'http://192.168.1.67:7001/edit',
              detailUrl: 'http://192.168.1.67:7001/detail2'
            }
          }
        }
        // importData()
        // console.log(e)
        e.form.importData(cached)
      }
    }

    function handleFormSubmit(form) {
      ctx.emit('submit', form)
    }

    async function saveLocalStorage() {
      await ZY_EXT.store.setItem(DB_NAME, cached)
    }

    function exportStorage() {
      let b = new Blob([ZY.JSON5.stringify(cached)], {type: "text/plain;charset=utf-8"});
      ZY_EXT.saveAs(b, 'arr.json')
    }

    return {
      control,
      saveLocalStorage,
      exportStorage,
      handleFormSubmit
    }
  }
}
</script>

<style scoped>

</style>
